<?php
declare(strict_types=1);

namespace app\console\model\activity;

use app\common\enum\order\OrderStatus;
use app\common\enum\order\PayStatus;
use app\common\model\activity\{Goods as GoodsModel, LuckyBag, Order as OrderModel};
use app\common\model\PaymentLog;
use think\facade\Db;


class Order extends OrderModel
{

    /**
     * @param string $orderNo
     * @return bool
     * @throws \Exception
     */
    public function closeOrder(string $orderNo): bool
    {
        try {
            $order = $this->where(['order_no' => $orderNo, 'order_source' => 1])->field('order_id,store_id,user_id,pay_price,pay_status,order_source,source_id')->lock(true)->find();
            if ($order->pay_status == PayStatus::SUCCESS) {
                throw new \Exception("订单已付款");
            }
            // 库存恢复
            $count = GoodsModel::where('order_id', $order->order_id)->count('goods_id');
            $res   = LuckyBag::update([
                'sale'  => Db::raw('sale-' . $count),
                'stock' => Db::raw('stock+' . $count)
            ], ['activity_id' => $order->source_id]);
            if (!$res) {
                throw new \Exception("更新库存失败");
            }
            // 取消预定商品
            $res = GoodsModel::update(
                ['order_id' => 0, 'status' => 0, 'user_id' => 0, 'select_index' => 0],
                ['order_id' => $order->order_id]
            );
            if (!$res) {
                throw new \Exception("更新商品失败 ==>" . $orderNo);
            }
            // 更新订单状态
            $order->pay_status   = 0;
            $order->order_status = OrderStatus::CANCELLED;
            $order->save();
            // 更新付款记录状态
            PaymentLog::update(['pay_status' => PaymentLog::PAY_FAIL], ['order_no' => $orderNo]);
            return true;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }
}